<template>
  <view class="form-container">
    <uni-forms ref="form" :model="formData" :rules="rules" :show-message="false">
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="staff" size="18" color="#409eff"></uni-icons>
          <text>角色信息</text>
        </view>

        <view class="form-group">
          <view class="form-label required">角色名称</view>
          <uni-forms-item name="roleName">
            <uni-easyinput v-model="formData.roleName" placeholder="请输入角色名称" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">权限字符</view>
          <uni-forms-item name="roleKey">
            <uni-easyinput v-model="formData.roleKey" placeholder="请输入权限字符" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">显示排序</view>
          <uni-forms-item name="roleSort">
            <uni-easyinput v-model="formData.roleSort" type="number" placeholder="请输入显示排序" :disabled="isView" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">数据范围</view>
          <uni-forms-item name="dataScope">
            <picker @change="handleDataScopeChange" :value="dataScopeIndex" :range="dataScopeOptions" range-key="text" :disabled="isView">
              <view class="picker-box" :class="{ 'is-disabled': isView }">
                <text>{{ dataScopeOptions[dataScopeIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">角色状态</view>
          <uni-forms-item name="status">
            <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="text" :disabled="isView">
              <view class="picker-box" :class="{ 'is-disabled': isView }">
                <text>{{ statusOptions[statusIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">备注</view>
          <uni-forms-item name="remark">
            <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
          </uni-forms-item>
        </view>
      </view>

      <!-- 菜单权限卡片 -->
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="list" size="18" color="#409eff"></uni-icons>
          <text>菜单权限</text>
        </view>

        <view class="menu-tree">
          <template v-if="menuLoading">
            <view class="loading-box">
              <text>加载中...</text>
            </view>
          </template>
          <template v-else>
            <xlam-tree
              :data="menuOptions"
              :value="formData.menuIds"
              :defaultStrictly="formData.menuCheckStrictly"
              @update:defaultStrictly="handleStrictlyChange"
              @change="handleMenuChange"
            />
          </template>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="form-actions" v-if="!isView">
        <button class="submit-btn" type="primary" @click="submitForm">确 定</button>
        <button class="cancel-btn" @click="cancel">取 消</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { addRole, updateRole, getRole, getMenuTree, getRoleMenuTree } from '@/api/system/role'
import XlamTree from '@/components/XlamTree/index.vue'

export default {
  components: {
    XlamTree
  },
  data() {
    return {
      formData: {
        roleId: '',
        roleName: '',
        roleKey: '',
        roleSort: 0,
        dataScope: '1',
        status: '0',
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: '',
        menuIds: []
      },
      rules: {
        roleName: {
          rules: [{ required: true, errorMessage: '请输入角色名称' }]
        },
        roleKey: {
          rules: [{ required: true, errorMessage: '请输入权限字符' }]
        },
        roleSort: {
          rules: [{ required: true, errorMessage: '请输入显示排序' }]
        }
      },
      dataScopeOptions: [
        { text: '全部数据权限', value: '1' },
        { text: '自定数据权限', value: '2' },
        { text: '本部门数据权限', value: '3' },
        { text: '本部门及以下数据权限', value: '4' },
        { text: '仅本人数据权限', value: '5' }
      ],
      statusOptions: [
        { text: '正常', value: '0' },
        { text: '停用', value: '1' }
      ],
      dataScopeIndex: 0,
      statusIndex: 0,
      title: '',
      isView: false,
      menuOptions: [],
      menuLoading: true,
    }
  },
  created() {
    // 确保选项数据已经初始化
    this.dataScopeIndex = this.dataScopeOptions.findIndex(item => item.value === this.formData.dataScope)
    this.statusIndex = this.statusOptions.findIndex(item => item.value === this.formData.status)
  },
  async onLoad(options) {
    this.menuLoading = true
    try {
      if (options.type === 'view') {
        this.isView = true
        this.title = '查看角色'
      }

      if (options.roleId) {
        if (!this.isView) {
          this.title = '修改角色'
        }
        this.formData.roleId = options.roleId.toString()
        await this.getDetail()
      } else {
        this.title = '新增角色'
        // 新增角色时使用 getMenuTree 获取菜单树
        const menuRes = await getMenuTree()
        if (menuRes.code === 200) {
          this.menuOptions = menuRes.data
        }
      }

      uni.setNavigationBarTitle({
        title: this.title
      })
    } catch (error) {
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.menuLoading = false
    }
  },
  methods: {
    // 获取角色详情
    async getDetail() {
      try {
        const [roleRes, menuRes] = await Promise.all([
          getRole(this.formData.roleId),
          getRoleMenuTree(this.formData.roleId)
        ])

        if (roleRes.code === 200) {
          Object.assign(this.formData, roleRes.data)
          this.dataScopeIndex = this.dataScopeOptions.findIndex(item => item.value === roleRes.data.dataScope)
          this.statusIndex = this.statusOptions.findIndex(item => item.value === roleRes.data.status)
        }

        if (menuRes.code === 200) {
          this.menuOptions = menuRes.data.menus
          this.formData.menuIds = Array.isArray(menuRes.data.checkedKeys) ?
            menuRes.data.checkedKeys :
            []

        }
      } catch (error) {
        uni.showToast({
          title: '获取角色详情失败',
          icon: 'none'
        })
      }
    },

    // 处理菜单选择
    handleMenuChange(selectedIds) {
      this.formData.menuIds = selectedIds
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate().then(async () => {
        try {
          const submitMethod = this.formData.roleId ? updateRole : addRole
          const result = await submitMethod(this.formData)

          if (result.code === 200) {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]

            if (prevPage && prevPage.$vm) {
              prevPage.$vm.handleQuery()
            }

            uni.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 1000
            })

            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        } catch (error) {
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      }).catch(errors => {
        const firstError = Object.values(errors)[0]?.errorMessage
        if (firstError) {
          uni.showToast({
            title: firstError,
            icon: 'none'
          })
        }
      })
    },

    // 数据范围改变
    handleDataScopeChange(e) {
      this.dataScopeIndex = e.detail.value
      this.formData.dataScope = this.dataScopeOptions[this.dataScopeIndex].value
    },

    // 状态改变
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.formData.status = this.statusOptions[this.statusIndex].value
    },

    // 取消
    cancel() {
      uni.navigateBack()
    },

    // 处理联动状态变化
    handleStrictlyChange(val) {
      this.formData.menuCheckStrictly = val
    }
  }
}
</script>

<style lang="scss">
.form-container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;

  .form-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

    .card-title {
      display: flex;
      align-items: center;
      margin-bottom: 36rpx;
      padding-bottom: 24rpx;
      border-bottom: 2rpx solid #f0f0f0;

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-left: 16rpx;
      }
    }

    .form-group {
      margin-bottom: 32rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        font-size: 28rpx;
        color: #606266;
        margin-bottom: 16rpx;
        font-weight: 500;

        &.required::before {
          content: '*';
          color: #f56c6c;
          margin-right: 8rpx;
        }
      }

      :deep(.uni-forms-item) {
        margin: 0;
        padding: 0;

        .uni-forms-item__content {
          .uni-easyinput__content {
            background-color: #f8f9fa;
            border-radius: 12rpx;
            height: 88rpx;
            padding: 0 28rpx;

            &.is-textarea {
              height: auto;
              padding: 20rpx 28rpx;

              textarea {
                font-size: 28rpx;
                color: #2c3e50;
                min-height: 160rpx;
              }
            }

            &.is-disabled {
              background-color: #f5f7fa;

              input {
                color: #909399;
              }
            }

            input {
              font-size: 28rpx;
              color: #2c3e50;

              &::placeholder {
                color: #909399;
              }
            }
          }
        }
      }

      .picker-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #f8f9fa;
        border-radius: 12rpx;
        height: 88rpx;
        padding: 0 28rpx;
        font-size: 28rpx;
        color: #2c3e50;

        &.is-disabled {
          background-color: #f5f7fa;
          color: #909399;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 32rpx;
    margin-top: 48rpx;
    padding: 0 30rpx;
    margin-bottom: 48rpx;

    button {
      flex: 1;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      border-radius: 44rpx;
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }

      &.submit-btn {
        background-color: #409eff;
        color: #fff;
        box-shadow: 0 8rpx 16rpx rgba(64,158,255,0.2);
      }

      &.cancel-btn {
        background-color: #f5f7fa;
        color: #606266;
        border: 2rpx solid #dcdfe6;
      }
    }
  }

  .menu-tree {
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 12rpx;
    min-height: 200rpx;

    .loading-box {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 200rpx;
      color: #909399;
      font-size: 28rpx;
    }
  }
}
</style>